import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:dio_cookie_manager/dio_cookie_manager.dart';
import 'package:cookie_jar/cookie_jar.dart';
import 'package:part_time_job_pro/common/exception/auth_interceptor.dart';
import 'package:part_time_job_pro/common/values/server_config.dart';
import 'package:part_time_job_pro/common/values/storage.dart';
import 'package:pretty_dio_logger/pretty_dio_logger.dart';

//dio请求封装
class HttpReq {
  //构造方法
  static final HttpReq _instance = HttpReq._internal();

  factory HttpReq() => _instance;

  Dio? _dio;

  Dio? get dio => _dio;

  /// 单例初始
  HttpReq._internal() {
    // header 头
    Map<String, String> headers = {
      contentTypeKey: contentType,
      acceptKey: accept,
      defaultLanguage: defaultLanguage,
      appPlatform: Platform.isAndroid ? "android" : "ios",
      appCodeKey: appCode,
      appVersionKey: appVersion,
    };

    // 初始选项
    var options = BaseOptions(
      baseUrl: HttpConfig.serverUrl,
      headers: headers,
      connectTimeout: const Duration(seconds: 5),
      // 5秒
      receiveTimeout: const Duration(seconds: 3),
      // 3秒
      responseType: ResponseType.json,
    );

    // 初始 dio
    _dio = Dio(options);
    // 拦截器 - 日志打印
    if (!kReleaseMode) {
      if (prettyLog) {
        //使用prettyDioLogger打印日志
        _dio?.interceptors.add(
          PrettyDioLogger(
            requestHeader: true,
            requestBody: true,
            responseBody: true,
            responseHeader: false,
            error: true,
            compact: false,
            enabled: kDebugMode,
            maxWidth: 280,
            logPrint: (str) => kDebugMode == true ? debugPrint("$str") : null,
          ),
        );
      } else {
        //使用默认打印日志
        _dio?.interceptors.add(
          LogInterceptor(
            requestBody: true,
            responseBody: true,
            logPrint: (str) => kDebugMode == true ? debugPrint("$str") : null,
          ),
        );
      }
    }

    //Cookie管理
    _dio?.interceptors.add(CookieManager(CookieJar()));
    //统一添加身份验证请求头
    _dio?.interceptors.add(AuthInterceptor());
  }
}
